<?php
require 'funct.headFootHtml.php';

function getUpgradeStatusVal() {
	return array('S'=>'Structural',
	'M'=>'Editable - not deletable',
	'C'=>'Editable and deletable',
	'D'=>'Deleted',
	'U'=>'Modified');
}

function goToPag($url){
	return "href=\"JavaScript:pageRedir('$url');\""; 	
}

function linkCmdHTML($aCmd, $aOpt=array()){
	global $objUser, $isReloadable;
	$bHavePerm = false;
	if(!isset($aCmd["text"]) || !isset($aCmd["pag"])){
		return '1';
	}
	$cmdPerm = (isset($aCmd["perm"]))?$aCmd["perm"]:"";
	if($cmdPerm == ""){
		$bHavePerm = true;
	} elseif($objUser->getPermission($cmdPerm) == "Y"){
		$bHavePerm = true;
	}
	if(!$bHavePerm){	
		return '2';
	}
	if (substr($aCmd["pag"],0,11)=='javascript:') {
		$hr = $aCmd["pag"];
	} else {
		if (substr($aCmd["pag"],-4)=='.php') {
			$hr = "javascript:pageRedir('".$aCmd["pag"]."?xsn=".XSN."');";
		} elseif(substr($aCmd["pag"],-1)=='?') {
			$hr = "javascript:pageRedir('".$aCmd["pag"]."xsn=".XSN."');";
		} elseif(substr($aCmd["pag"],-1)=='&') {
			$hr = "javascript:pageRedir('".$aCmd["pag"]."xsn=".XSN."');";
		} else {
			$hr = "javascript:pageRedir('".$aCmd["pag"]."&xsn=".XSN."');";
		}
	}
	$sHTML = "<a class=\"link01\" href=\"$hr\" ";
	if(isset($aCmd["title"]) and trim($aCmd["title"]) != '')
		$sHTML .= "alt=\"".$aCmd["title"]."\" title=\"".$aCmd["title"]."\"";
	else 
		$sHTML .= "alt=\"".$aCmd["text"]."\" title=\"".$aCmd["text"]."\"";
	$sHTML .= " style='white-space:nowrap;'>";
	$sHTML .= $aCmd["text"]."</a>";
	return $sHTML;
}

function getTitleLink($title,$aCmd) {
	$sHTML = "<tr>" .
		"<td class=\"titl01\"colspan=\"20\">".
		"<table cellspacing='0' cellpadding='0' width='100%'><tr>".
		"<td class=\"titl01\">$title</td>" .
		"<td class=\"titl01\" align='right'>".linkCmdHTML($aCmd)."</td>" .
		"</tr></table></td>".
	"</tr>\n";
	return $sHTML;
}

function linkBackHTML() {
	global $objUser, $isReloadable;
	if (!$isReloadable) {
		$hr = $objUser->getHistory(0);
		$tt = 'cancel';
		$sHTML = "<a class=\"link01\" href=\"$hr\" ";
		$sHTML .= "alt=\"$tt\" title=\"$tt\"";
		$sHTML .= " style='white-space:nowrap;'>$tt</a>";
	} else {
		$hr = $objUser->getHistory(-1);
		$tt = $objUser->getHistoryText(-1);
		$sHTML = "<a class=\"link01\" href=\"$hr\" ";
		$sHTML .= "alt=\"$tt\" title=\"$tt\"";
		$sHTML .= " style='white-space:nowrap;'>$tt</a>";
	}
	return $sHTML;
}

function commandsHTML($aCommands, $aOpt=array()){
	global $isReloadable, $objUser;
	//table of commands
	$objUser = $_SESSION[USEROBJ];
	$sep = "";
	$sHTML = "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border='0'>\n";
	$sHTML .= "<tr>\n";
	for($q=1;$q<=2;$q++) {
		if ($q==1)$sHTML .= "<td class=\"link01\" align='left'><b>";
		else      $sHTML .= "<td class=\"link01\" align='right'><b>";
		foreach($aCommands as $command=>$aCmd){	
			if ($q==1) {
				if (!isset($aCmd['align']) or $aCmd['align'] != 'L') {
					continue;
				}
			} else {
				if (isset($aCmd['align']) and $aCmd['align'] == 'L') {
					continue;
				}
			}
			if ($command == 'back' || $command == 'canc') {
				$sHTML .= $sep.linkBackHTML();
			} else {
				$sHTML .= $sep.linkCmdHTML($aCmd);
			}
			if($bVert){
				$sep = "<br>";
			}else{
				$sep = " ";
			}
		}
		$sHTML .= "</b></td>\n";
	}
	$sHTML .= "</tr>\n";
	$sHTML .= "</table>\n";
	return $sHTML;
}
function getHtmlForm($name='', $action='', $aOpt=array()) {
	$sEncType = ' enctype="multipart/form-data"';//(isset($aOpt['enctype']))?' enctype="multipart/form-data"':'';
	if ($action == '') {
		$action = $_SERVER['PHP_SELF'];
	}
	if ($name == '') {
		$name = 'frm1';
	}
	$sHtml = '<form name="'.$name.'" id="'.$name.'" action="'.$action.'" method="post"'
		.$sEncType." style='margin:0;padding:0;'>\n";
	return $sHtml;
}

function getHtmlTextCode($name, $size, $maxLen=0, $val='@REQ', $aOpt=array()) {
	if (!isset($aOpt['style'])) {
		$aOpt['style'] = "";
	}
	$aOpt['style'] .= 'font-family:lucida console,courier;';
	$sHtml = getHtmlText($name, $size, $maxLen, $val, $aOpt) ;
	return $sHtml;
}

function getHtmlTextNum($name, $size, $maxLen=0, $val='@REQ', $aOpt=array()) {
	if (!isset($aOpt['style'])) {
		$aOpt['style'] = "";
	}
	$aOpt['style'] .= 'text-align:right;';
	return getHtmlText($name, $size, $maxLen, $val, $aOpt);
} 

function getHtmlText($name, $size, $maxLen=0, $val='@REQ', $aOpt=array()) {
	$sOnChange = (isset($aOpt['onChange']))?' onChange="'.$aOpt['onChange'].'" ':'';
	$sReadOnly = (isset($aOpt['readonly']))?' READONLY':'';
	$sMaxLen = ($maxLen==0)?'':' maxlength="'.$maxLen.'"';
	$sStyle = (isset($aOpt['style']))?' style="'.$aOpt['style'].'"':'';
	$sVal = ($val=='@REQ')? sxRHE($name):htmlentities($val);
	$sSize = ' size="'.($size*1).'"';
	$sHtml = '<input type="text" class="inpt01" name="'.$name.'" id="'.$name.'" value="'.$sVal.'" '
		.$sSize.$sMaxLen.$sReadOnly.$sStyle.$sOnChange.">\n";
	return $sHtml;
}

function getHtmlDate($name, $val='@REQ', $nomeForm='frm1', $aOpt=array()) {
	$sReadOnly = (isset($aOpt['readonly']))?' READONLY':'';
	$sOnChange = (isset($aOpt['onChange']))?' onChange="'.$aOpt['onChange'].'" ':'';
	$sOpzSubm = ($sOnChange=='')?"":"submOrig=S&";
	$sMaxLen = '10';
	$sVal = ($val=='@REQ')? sxRHE($name):htmlentities($val);
	$sHtml = "<input type=\"text\" class=\"inpt01\" name=\"$name\" id=\"$name\" value=\"$sVal\"".
		" size=\"8\" maxlength=\"10\" $sReadOnly $sOnChange>".
		"&nbsp;<img src='".PF_URL_BASE."/app/_img/calendario.png' " .
		"style='text-decoration:underline;cursor:pointer;'  onClick=\"apriCalend_$nomeForm$name();\" />\n";
	$sHtml .= "<script>";
	$sHtml .= "function apriCalend_$nomeForm$name() {\n" .
		"dtVal = encodeURIComponent(document.$nomeForm.$name.value);\n".
		"window.open('".PF_URL_BASE."/app/calendario.php?$sOpzSubm" .
		"nome_form=$nomeForm&nome_campo=$name&dt='+dtVal+'&xsn=".XSN."'" .
		",'Calendario','top=200,left=100,width=290,height=240," .
		"resizable=yes,titlebar=no,location=no,location=no,menubar=no,toolbar=no');\n".		
			"}\n";
	$sHtml .= "</script>\n";
	
	return $sHtml;
}

function getHtmlPassword($name, $size, $maxLen=0, $val='@REQ', $aOpt=array()) {
	$sReadOnly = (isset($aOpt['readonly']))?' READONLY':'';
	$sMaxLen = ($maxLen==0)?'':' maxlength="'.$maxLen.'"';
	$sVal = ($val=='@REQ')? sxRHE($name):htmlentities($val);
	$sHtml = '<input type="password" class="inpt01" name="'.$name.'" id="'.$name.'" ' .
			' value="'.$sVal.'" size="'.$size.'"'.
		$sMaxLen.$sReadOnly.' style="font-family:lucida console,courier">'."\n";
	return $sHtml;
}

function getHtmlFile($name, $size, $aOpt=array()) {
	$sHtml = '';//<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />';
	$sHtml .= '<input type="file" class="inpt01" name="'.$name.'" id="'.$name.'" size="'.$size."\">\n";
	return $sHtml;
}

function getHtmlTextArea($name, $cols=80, $rows=5, $val='@REQ', $aOpt=array()) {
	$sReadOnly = (isset($aOpt['readonly']))?' READONLY':'';
	$sClass = (isset($aOpt['class']))?$aOpt['class']:'inpt01';
	$sStyle = (isset($aOpt['style']))?' style="'.$aOpt['style'].'"':'';
	$sVal = ($val=='@REQ')? sxRHE($name):htmlentities($val);
	$sHtml = '<textarea class="'.$sClass.'" name="'.$name.'" id="'.$name.'" ' 
		.'cols="'.$cols.'" rows="'.$rows.'"'.$sReadOnly.$sStyle.'>'
		.$sVal.'</textarea>'."\n";
	return $sHtml;
}

function getHtmlTextAreaScript($name, $cols=80, $rows=5, $val='@REQ', $aOpt=array()) {
	if (!isset($aOpt['style'])) {
		$aOpt['style'] = 'font-family:courier;';
	} else {
		$aOpt['style'] .= 'font-family:courier;';
	}
	return getHtmlTextArea($name, $cols, $rows, $val, $aOpt);
}


function getHtmlVisText($nome,$aOpt=array()) {
	return htmlentities(sxREQ($nome));
}

function getHtmlPreText($nome,$aOpt=array()) {
	$s = wordwrap(sxREQ($nome),75,"\n",true);
	return "<pre>".htmlentities($s)."</pre>";
}

function getHtmlPreScript($nome,$aOpt=array()) {
	$s = wordwrap(sxREQ($nome),75,"\n",true);
	return "<pre style='font-family:courier;'>".htmlentities($s)."</pre>";
}

function getHtmlVisCode($nome) {
	$sHtml = "<span style=\"font-family:lucida console,courier\">".
	getHtmlVisText($nome)."</span>";
	return $sHtml;
}

function getHtmlVisNote($nome,$aOpt=array()) {
	return getHtmlPreText($nome,$aOpt);
}

function getHtmlVisScript($nome,$aOpt=array()) {
	return getHtmlPreScript($nome,$aOpt);
}

function getHtmlVisNum($nome,$nDec,$leftZero=0) {
	return num2str(sxREQ($nome),$nDec,$leftZero);
}

function getHtmlVisDecode($nome,$aVal) {
	return (isset($aVal[sxREQ($nome)]))?$aVal[sxREQ($nome)]:sxREQ($nome);
}

function getHtmlRadio($name, $aVal, $val='@REQ', $aOpt=array()) {
	$sVal = ($val=='@REQ')? sxREQ($name):$val;
	$sHtml='';
	$sSep = (isset($aOpt['aCapo']) and $aOpt['aCapo'])?"<br>\n":"&nbsp;&nbsp;&nbsp;\n";
	$sOnClick = (isset($aOpt['onClick']) and $aOpt['onClick'])?" onClick=\"".$aOpt['onClick']."\"":"";
	$i = 1;
	foreach($aVal as $vX => $dX) {
		$chk = ($sVal == $vX)?' checked':'';
		$sHtml .= '<input type="radio" id="'.$name."_".$i.'" name="'.$name.'" value="'.htmlentities($vX).'"'.$chk.$sOnClick.
			' class="inpt01">&nbsp;'.htmlentities($dX).$sSep;
		$i ++;
	}
	return $sHtml;
}

function getHtmlCheckBox($name, $valChecked, $val='@REQ', $aOpt=array()) {
	$sVal = ($val=='@REQ')? sxREQ($name):$val;
	$sOnClick = (isset($aOpt['onClick']) and $aOpt['onClick'])?" onClick=\"".$aOpt['onClick']."\"":"";
	$sHtml='';
	$chk = ($sVal == $valChecked)?' checked':'';
	$sHtml .= '<input type="checkBox" id="'.$name.'" name="'.$name.'" ' .
			'value="'.htmlentities($valChecked).'" '.$chk.' class="inpt01" '.$sOnClick.">\n";
	return $sHtml;
}

function getHtmlSelect($name, $aVal, $val='@REQ', $aOpt=array()) {
	$sVal = ($val=='@REQ')? sxREQ($name):$val;
	$sDisabled = (isset($aOpt['disabled']))?' disabled':'';
	$sOnChange = (isset($aOpt['onChange']))?' onChange="'.$aOpt['onChange'].'"':'';
	$style = (isset($aOpt['style']))?' style="'.$aOpt['style'].'"':'';
	$sHtml= "<select class=\"inpt01\" id=\"$name\" name=\"$name\" $sOnChange $style $sDisabled>";
	foreach($aVal as $vX => $dX) {
		$sel = ($sVal == $vX)?' selected':'';
		$sHtml .= "<option value=\"".htmlentities($vX)."\"$sel>$dX</option>";
	}
	$sHtml.= "</select>\n";
	return $sHtml;
}

function getHtmlSelectMult($name, $aVal, $val='@REQ', $aOpt=array()) {
	$sVal = ($val=='@REQ')? sxREQ($name):$val;
	$sOnChange = (isset($aOpt['onChange']))?' onChange="'.$aOpt['onChange'].'"':'';
	$sHtml='<select class="inpt01" id="'.$name.'_cmbx" name="'.$name.'_cmbx"'.' size="5"' .
			' onClick="setSelMult_'.$name.'();">';
	foreach($aVal as $vX => $dX) {
		$sHtml .= '<option value="'.htmlentities($vX).'">'.htmlentities($dX).'</option>';
	}
	$sHtml.='</select>'."\n";
	$sHtml .= '<textarea class="inpt01" name="'.$name.'" id="'.$name.'" cols="40" rows="5" readonly>'.
		$sVal.'</textarea>'."\n";
	$sHtml .= "<script>\n" .
			"function setSelMult_$name() {\n" .
			"   oTesto = document.getElementById('$name');\n" .
			"   oCombo = document.getElementById('".$name."_cmbx');\n" .
			"   selk = oCombo.selectedIndex;\n".
			"   tnew = oCombo.options[selk].value;\n".
			"   //alert(oTesto.value+tnew);\n".
			"   if (oTesto.value.search(tnew+';') < 0) {\n".
			"	   oTesto.value = oTesto.value+oCombo.options[selk].value+'; ';\n".
			"   } else {\n".
			"     oTesto.value = oTesto.value.replace(tnew+';','');\n".			
			"   }\n".
			"   oTesto.value = oTesto.value.replace('  ',' ');\n".			
			"}\n" .
			"</script>\n";
	return $sHtml;
}

function getHtmlHidden($name, $val='@REQ', $aOpt=array()) {
	$sVal = ($val=='@REQ')? sxRHE($name):htmlentities($val);
	$sHtml = '<input type="hidden" name="'.$name.'" id="'.$name.'" value="'.$sVal.'" />'."\n";
	return $sHtml;
}

/**
 * HTML per la paginreqtype
 * per default vengono considerate 15 rec per pagina
 * il valore pu@ essere aumentato o diminuito di 5 (da 5 a 100) 
 * e viene memorizzato in base_parametro a livello utente/processo
 * utilizza due variabili GET/POST: 
 * 			startoffset = numero rec. inizio (0 = primo record)
 * 			pagifilt    = stringa filter
 * Parametri:
 * 	link = href della pagina con tutte le variabili GET
 * 	numRec = numero totale record
 * 	startOffset = 	primo record da visualizzare - 
 * 						parametro restituito per referenza - il valore fornito viene ignorato
 * 	endOffset = 	primo record da non visualizzare - 
 * 						parametro restituito per referenza - il valore fornito viene ignorato
 * 	filter = 		se true viene predisposta la gestione del campo filter (variabile pagifilt)
 */
function sxGetPaginaz($link, $numRec, &$startOffset, &$endOffset){
	global $objSDAO;
	$startOffset = intval(sxREQUEST('startoffset'));
	$recPerPag = 15;
	// legge da base_parametro il num. rec. per pagina
	$idUt = (defined('ID_UTENTE'))?ID_UTENTE:0;
	$sSQL = "SELECT valore FROM param " .
			" WHERE  id_user = $idUt AND cod = 'recxpag_".sxAS($_SERVER['PHP_SELF'])."'";
	$objSDAO->query($sSQL,'recxpag');
	if ($row=$objSDAO->fetch('recxpag')) {
		$recPerPag = intval($row['valore']);
		if ($recPerPag < 5) $recPerPag = 5;
	}
	// se passato recperpag modifica il numero rec. per pagina e lo memorizza
	if (sxREQUEST('recperpag')=='piu5' and $recPerPag < 100) {
		$recPerPag += 5;
		$sSQL = "DELETE FROM param " .
				" WHERE id_user = $idUt AND cod = 'recxpag_".sxAS($_SERVER['PHP_SELF'])."'";
		$objSDAO->exec($sSQL);
		if ($recPerPag != 15) {
			$sSQL = "INSERT INTO param SET valore = $recPerPag, " .
					" id_user = $idUt, cod = 'recxpag_".sxAS($_SERVER['PHP_SELF'])."'";
			$objSDAO->exec($sSQL);
		}
	}
	if (sxREQUEST('recperpag')=='meno5' and $recPerPag > 9) {
		$recPerPag -= 5;
		$sSQL = "DELETE FROM param " .
				" WHERE id_user = $idUt AND cod = 'recxpag_".sxAS($_SERVER['PHP_SELF'])."'";
		$objSDAO->exec($sSQL);
		if ($recPerPag != 15) {
			$sSQL = "INSERT INTO param SET valore = $recPerPag, " .
					" id_user = $idUt, cod = 'recxpag_".sxAS($_SERVER['PHP_SELF'])."'";
			$objSDAO->exec($sSQL);
		}
	}
	
	$endOffset = $startOffset + $recPerPag;
	if ($endOffset > $numRec) $endOffset = $numRec;
	$lastPage = ceil($numRec / $recPerPag);
	$currPage = ceil(($startOffset+1) / $recPerPag);
	if ($currPage < 4) {
		$iStart = 1; 
	} else {
		$iStart = $currPage - 3; 
	}
	$iEnd = $iStart + 6;
	if ($iEnd > $lastPage) $iEnd = $lastPage;
	if  ($iEnd > 6) $iStart = $iEnd - 6;
	$sHTML = "";
	$sHTML .= "<table cellpadding=\"0\" cellspacing=\"0\" class=\"tabl01\" width=\"100%\">";
		$sHTML .= "<tr>\n";
	// aggiunge var. GET per filter 
	$linkPf = $link."&pagifilt=".urlencode(sxREQUEST('pagifilt'));
	$sHTML .= "<td class='page01' align='right'>$numRec record - pag. $currPage di $lastPage &nbsp;&nbsp;&nbsp;";
	if ($lastPage > 1) {
		if ($currPage > 1) {
			$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=0\" title=\"prima pagina\">" .
					"<img src='".SERVER_URL_ROOT."/app/_img/freccia_stop_sx.gif' border='0'></a>&nbsp;";
			$offset = ($currPage - 2) * $recPerPag;
			$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=$offset\" title=\"pagina precedente\">" .
					"<img src='".SERVER_URL_ROOT."/app/_img/freccia_sx.gif' border='0'></a>&nbsp;";
		} else {
			$sHTML .= "<img src='".SERVER_URL_ROOT."/app/_img/freccia_stop_sx_grigia.gif' border='0'>&nbsp;";
			$sHTML .= "<img src='".SERVER_URL_ROOT."/app/_img/freccia_sx_grigia.gif' border='0'>&nbsp;";
		} 
		for($i=$iStart;$i<=$iEnd;$i++) {
			if ($i == $currPage) {
				$sHTML .= "<b>$i</b>&nbsp;";
				continue;
			}
			$offset = ($i - 1)* $recPerPag;
			$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=$offset\" title=\"pagina $i\">$i</a>&nbsp;";
		}
		if ($currPage < $lastPage) {
			$offset = $currPage * $recPerPag;
			$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=$offset\" title=\"pagina successiva\">" .
					"<img src='".SERVER_URL_ROOT."/app/_img/freccia_dx.gif' border='0'></a>&nbsp;";
			$offset = ($lastPage - 1) * $recPerPag;
			$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=$offset\" title=\"ultima pagina\">" .
					"<img src='".SERVER_URL_ROOT."/app/_img/freccia_stop_dx.gif' border='0'></a>";
		} else {
			$sHTML .= "<img src='".SERVER_URL_ROOT."/app/_img/freccia_dx_grigia.gif' border='0'>&nbsp;";
			$sHTML .= "<img src='".SERVER_URL_ROOT."/app/_img/freccia_stop_dx_grigia.gif' border='0'>";
		} 
	}
	$sHTML .= "&nbsp;&nbsp;&nbsp;";
	if ($recPerPag > 9 ) {
		$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=0&recperpag=meno5\" " .
			"title=\"diminuisce a ".($recPerPag-5)." il numero righe per pagina\">".
			"<img src='".SERVER_URL_ROOT."/app/_img/meno.gif' border='0'></a>&nbsp;";
	}
	if ($recPerPag < 100 ) {
		$sHTML .= "<a class='page01' href=\"$linkPf&startoffset=0&recperpag=piu5\" " .
			"title=\"aumenta a ".($recPerPag+5)." il numero righe per pagina\">" .
			"<img src='".SERVER_URL_ROOT."/app/_img/piu.gif' border='0'></a>";
	}
	$sHTML .= "&nbsp;";
	$sHTML .= "</td></tr>";
	$sHTML .= "</table>";
	return $sHTML;
}

function sxGetFilter($link){
	$sHTML = "";
	$sHTML .= "<table cellpadding=\"3\" cellspacing=\"3\" class=\"tabl01\" width=\"100%\">\n";
	$sHTML .= "<tr>\n";
	$sHTML .= "<td class='text01' align='left'>Filter:\n";
	$sHTML .= "<input type='text' name='pagifilt' id='pagifilt' value=\"".sxRHE('pagifilt').
		"\" size='20' class='inpt01'>&nbsp;\n";
	$sHTML .= "<a class='link01' href='#' onclick=\"javascript:oPgFlt=document.getElementById('pagifilt');" .
		"document.location.href='$link&pagifilt='+encodeURI(oPgFlt.value)+'&startoffset=0';\" " .
		"title=\"set filter\" style='cursor:pointer;text-decoration:underline;'>" .
		"set</a>&nbsp;\n";
	$sHTML .= "<a class='link01' href='#' onclick=\"document.location.href='$link&pagifilt=&startoffset=0';\" " .
		"title=\"cancel filter\" style='cursor:pointer;text-decoration:underline;'>" .
		"cancel</a>&nbsp;\n";
	$sHTML .= "</td>\n";
	$sHTML .= "</tr>\n";
	$sHTML .= "</table>\n";
	return $sHTML;
}

function headerDownload($lung, $fileName) {
	header("Pragma: public"); 
	header("Expires: 0"); 
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	header("Cache-Control: private",false); 
	header("Content-Type: application/".substr($fileName,-3)); 
	header("Content-Transfer-Encoding:  binary"); 
	header('Content-Length: '.$lung);
	header('Content-disposition: attachment; filename="'.$fileName.'"');
}
